/**
 * Created by leo on 10/25.
 */
(function () {
    'use strict';
    angular.module('templates', []);
    angular.module('portalApp', ['Menu', 'Nav', 'Tab', 'QuickSearch', 'panels', 'templates', 'News'])
        .config(function ($sceProvider, $logProvider) {
            $sceProvider.enabled(false);
            $logProvider.debugEnabled(false);
        })
        .value("urlPrefix", "../")
        .value("titlePrefix", "BOMC门户 - ")
        .controller('MainCtrl', function ($window) {
            $window.onbeforeunload = function () {
                return "您确定要离开本页面吗？";
            }
        })
        .constant('AddMessageListener', function (callback) {
            return this.attachEvent ? this.attachEvent('onmessage', callback) : this.addEventListener('message', callback);
        })
        .run(function ($window, $log, $rootScope, tabService, AddMessageListener) {
            // tab切换时向相关的iframe发送通知
            tabService.onTabSwitched(function (currentTab, oldTab) {
                $log.debug('switch tab: ', currentTab, oldTab);
                angular.forEach(arguments, function (tab) {
                    if (tab) {
                        var iframe = angular.element('[id="' + tab.id + '"] iframe').get(0);
                        if (iframe) iframe.contentWindow.postMessage('TAB_SWITCH?' + (tab === currentTab ? 'ON' : 'OFF'), '*');
                    }
                });
            });
            var timestamp = new Date().getTime(); // 只初始化一次的时间戳,解决portal-api.min.js缓存问题
            AddMessageListener.call($window, function (e) {
                $log.debug('message:', e.data);
                var message = e.data, sourceWindow = e.source,
                    findIframe = function (sourceWindow) {
                        var frames = document.getElementsByTagName('iframe');
                        for (var i = 0; i < frames.length; i++) {
                            if (frames[i].contentWindow === sourceWindow) {
                                return frames[i];
                            }
                        }
                    };
                var match, frame;
                if (message === 'REQUEST:PORTAL_API') { // 使iframe内的页面加载portal-api.js
                    var api = location.href.replace(/[^\/]+$/, '') + '/portal-api.min.js?' + timestamp;
                    if (findIframe(sourceWindow)) {
                        sourceWindow.postMessage('RESPONSE:PORTAL_API=' + api, '*');
                    }
                } else if (match = message.match(/^IFRAME_RESIZE\?height=(\d+)$/)) { // 接收iframe同步请求
                    frame = findIframe(sourceWindow);
                    if (frame) {
                        frame.style.height = Math.max(match[1], document.documentElement.clientHeight - frame.offsetTop - 4) + 'px';
                    }
                } else if (match = message.match(/^IFRAME_LOADED\?title=(.+)&url=(.+)$/)) { // 接收iframe的文档标题
                    frame = findIframe(sourceWindow);
                    var tabIndex = parseInt(frame.getAttribute('data-index'));
                    if (frame && tabIndex === tabService.activeTab()) {
                        $rootScope.$apply(function () {
                            var tab = tabService.currentTab();
                            var tabUrl = document.createElement('a');
                            var realUrl = document.createElement('a');
                            tabUrl.href = tab.url;
                            // noinspection SillyAssignmentJS : IE8 fixed
                            tabUrl.href = tabUrl.href;
                            realUrl.href = decodeURIComponent(match[2]);
                            tab.name = tabUrl.host == realUrl.host && tabUrl.pathname == realUrl.pathname ? tab.initName : decodeURIComponent(match[1]);
                            tabService.activeTab(tabIndex); // 更新document.title
                        });
                    }
                } else if (message.indexOf('TAB_ADD?') == 0) { // 创建tab
                    var params = {};
                    angular.forEach(message.split('?')[1].split('&'), function (param) {
                        var split = param.split('=');
                        params[split[0]] = decodeURIComponent(split[1]);
                    });
                    if (params.name && params.url) {
                        tabService.addTab(params);
                        $rootScope.$apply();
                    }
                } else if (message == 'TAB_REMOVE') {
                    frame = findIframe(sourceWindow);
                    if (frame) {
                        tabService.removeTab(frame.getAttribute('data-index'));
                        $rootScope.$apply();
                    }
                } else if (message.indexOf('REFRESH_PANEL:') == 0) {
                    $rootScope.$broadcast("reload-panel", message.split(":")[1]);
                }
            });

            $rootScope.$on('showBodyScroll', function (event, status) {
                $rootScope.bodyScroll = status;
            });
        });
}());